// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        l1: cc.Node, //左侧背景1
		l2: cc.Node, //左侧背景2
		r1: cc.Node, //右侧背景1
		r2: cc.Node, //右侧背景2
		speed: 50, //背景移动速度
		player: cc.Node, //机器人节点
		jump: true, //是否可以跳
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
		this.node.on(cc.Node.EventType.TOUCH_START,this.onTouchStart,this)
		// 获取重置触发坐标点
		this.triggerLY = -this.l1.height;
		this.triggerRY = -this.r1.height;
	},
	onTouchStart (event) {
		console.log('点击屏幕');
		if(!this.jump){
			return;
		}
		// 点击后就不让点击，直到动作执行完成
		this.jump = false;
		
		var touchLoc = event.getLocation();
        if (touchLoc.x >= cc.winSize.width/2) {
            // 向右
			this.playerMoveRight();
        } else {
            // 向左
			this.playerMoveLeft();
        }	
		
		this.bgMove();
	},
	playerMoveLeft () {
		console.log('向左跳跃');
		// 用0.1秒的时间，向上移动100px
		var up = cc.moveTo(0.1,cc.Vec2(this.player.x,this.player.y+100));
		// 用0.1秒的时间, 向下移动100px
		var down = cc.moveTo(0.1,cc.Vec2(this.player.x,this.player.y));
		// 执行回调
		var callback = cc.callFunc(this.jumpIsOver, this); 
		// 先向上移动，再向下移动
		var jump = cc.sequence(up,down,callback);
		// 执行动作
        this.player.runAction(jump);
		// X轴翻转，1表示正向，-1表示反向
		this.player.scaleX = 1;
    },
	jumpIsOver () {
		console.log('跳跃完成');
		// 跳跃完成，可以点击
		this.jump = true;
	},
	playerMoveRight () {
		console.log('向右跳跃');
		// 用0.1秒的时间，向上移动100px
		var up = cc.moveTo(0.1,cc.Vec2(this.player.x,this.player.y+100));
		// 用0.1秒的时间, 向下移动100px
		var down = cc.moveTo(0.1,cc.Vec2(this.player.x,this.player.y));
		// 执行回调
		var callback = cc.callFunc(this.jumpIsOver, this); 
		// 先向上移动，再向下移动
		var jump = cc.sequence(up,down,callback);
		// 执行动作
        this.player.runAction(jump);
		// X轴翻转，1表示正向，-1表示反向
		this.player.scaleX = -1;
    },
	bgMove () {
		// 背景移动
		this.l1.y -= this.speed;
		this.l2.y -= this.speed;
		
		this.r1.y -= this.speed;
		this.r2.y -= this.speed;
 
		// 重置
		if (this.l1.y <= this.triggerLY) 
			this.l1.y = this.l2.y+this.l1.height;
		else if (this.l2.y <= this.triggerLY) 
			this.l2.y = this.l1.y+this.l1.height;
		
		if (this.r1.y <= this.triggerRY) 
			this.r1.y = this.r2.y+this.r1.height;
		else if (this.r2.y <= this.triggerRY) 
			this.r2.y = this.r1.y+this.r1.height;
	},
    start () {

    },

    // update (dt) {},
});
